window.CardLove= window.CardLove || {};

CardLove.Game = CardLove.Game || {
    //开始
    start : false,
    //暂停
    pause : false,
    //结束
    finish : false,


    system : null,

    player : null,

    //排序时间统计
    _sortTime : 0,
    //排序循环标识
    sortFlag : false,

    //记忆卡片时间
    _memoryTime : 0,
    //记忆卡片循环标识
    _memoryFlag : false,

    //系统分牌前的时间间隔
    _showSysCardTime : 0,
    //分牌时间标识
    _showSysCardFlag : false,

    _pickerTime : 0,

    _pickerCardFlag : false,

    pickedCard : null,

    //debug
    debug : true
};

CardLove.Game.init = function(){

    //初始化角色对象
    CardLove.Game.player = CardLove.Role.initRole();
    CardLove.Game.system = CardLove.Role.initRole();


    //初始化所有图片
    CardLove.Game.initSysCards();


	CardLove.Game.initCanvas();


    //点击开始游戏
    $("#btn_start").click(function(){

        //系统随机发牌给角色

        //用户自定义card排序

        CardLove.Game.start();
    });

	//绑定用户操作事件  主要事件逻辑处理
    CardLove.Card.bindEvent(function(e){
    	e.stopPropagation();
    	e.preventDefault();
    	var node = e.currentTarget;
    	var imgNode = node.getElementsByTagName('img')[0]; //当前触发事件的容器
    	var mode = CardLove.Config.game.mode;//当前游戏mode
    	var _cache = CardLove.Card._cache;
		var cardInfo = CardLove.Game._getCardInfo(imgNode); //节点容器信息
		var flag = 0 ;
		var nodeInfo = CardLove.Config.imgList.node[flag];
		var card = _cache.cards[cardInfo.id];//获取当前的card对象
    	switch(mode){
    		case '-1' :{//现在不能选牌
    			break;
    		}
    		case '0' : {
    			CardLove.Game.exchangeCard(node,true,{_cache: _cache, cardInfo : cardInfo,flag : flag,nodeInfo :nodeInfo ,card : card});
    			break;
    		}
    		case '1' : {
    			clearTimeout(CardLove.Game._pickerCardFlag);
    			CardLove.Game.selectCard(node,true,{_cache: _cache, cardInfo : cardInfo,flag : flag,nodeInfo :nodeInfo ,card : card});
    			break;
    		}
    		case '2' : {
    			CardLove.Game.exchangeCard(node,true,{_cache: _cache, cardInfo : cardInfo,flag : flag,nodeInfo :nodeInfo ,card : card});
    			break;
    		}
    	}
    	return false;
    });


};


/**
 * 初始化系统cards
 */
CardLove.Game.initSysCards = function(){
    CardLove.Card.initCard();
};


/**
 * 开始
 */
CardLove.Game.start = function(){
    //setTimeout("CardLove.Game.start()",3000);

    //开始发牌
    if(this.debug) debug.info("系统正在发牌...");
    CardLove.Config.step = 0;
    CardLove.Game.showStatus({
        msg:"系统正在发牌给你...",
        time: 0,
        color:"#FFF"
    });
    CardLove.Game.system.cards = CardLove.Card.getRoleCard().sys;
    CardLove.Game.player.cards = CardLove.Card.getRoleCard().player;
    if(this.debug) debug.info(CardLove.Game.player);
    

    //开始排序
    CardLove.Game.roleSortCard();
};


/**
 * 暂停（预留接口）
 */
CardLove.Game.pause = function(){

};


/**
 * 结束游戏
 */
CardLove.Game.finish = function(){

};

/**
 * 第二步：用户排序card牌10秒
 */
CardLove.Game.roleSortCard = function(){
    if(CardLove.Game.debug) debug.info("你正在排序Card牌，第" + CardLove.Game._sortTime + "秒");
    //判断排序时间是否完成
    if(this._sortTime == 0 || this._sortTime < CardLove.Config.timer.roleSortCardTimer){

        //加入排序逻辑
        CardLove.Config.game.mode = "0";
        CardLove.Config.step = -1;
        CardLove.Game.showStatus({
            msg:"置牌时间，剩下：",
            time:CardLove.Config.timer.roleSortCardTimer - this._sortTime,
            color:"#FFF"
        });

        this._sortTime++;
        this.sortFlag = setTimeout("CardLove.Game.roleSortCard()",1000);
    }else{
        clearTimeout(this.sortFlag);
        CardLove.Game.memoryCard();
    }
};
/**
 * 第三步：记忆card牌30秒
 */
CardLove.Game.memoryCard = function(){
    if(this.debug) debug.info("你正在记忆card牌位置，当前第" + this._memoryTime + "秒");
    if(this._memoryTime == 0 || this._memoryTime < CardLove.Config.timer.memoryTimer){

        //在这里加入逻辑
        CardLove.Config.game.mode = "-1";
        CardLove.Config.step = 2;
        CardLove.Game.showStatus({
            msg:"现在是记牌时间，剩下",
            time:CardLove.Config.timer.memoryTimer - this._memoryTime,
            color:"#FFF"
        })

        this._memoryTime++;
        this._memoryFlag = setTimeout("CardLove.Game.memoryCard()",1000);
    }else{
        clearTimeout(this._memoryFlag);
        CardLove.Game.showSysCard();
    }
};

/**
 * 第四步：显示一张系统card牌
 */
CardLove.Game.showSysCard = function(){
    if(this.debug) debug.info("系统准备发牌，当前第" + this._showSysCardTime + "秒");


    //判断赢了吗
    if(CardLove.Game.isWin()){
        clearTimeout(this._showSysCardFlag);
        CardLove.Game.showStatus({
            msg:"呼～你输给了计算机。",
            time:0,
            color:'#00FFFF'
        });
       
    }else if(CardLove.Game.isLose()){
        clearTimeout(this._showSysCardFlag);
        CardLove.Game.showStatus({
            msg:"亲～恭喜你，你赢了计算机。",
            time:0,
            color:'#00FFFF'
        });
         return false;
    }

    if(this._showSysCardTime == 0 || this._showSysCardTime < CardLove.Config.timer.showSysCardTimer){

        //在这里加入逻辑
        CardLove.Config.game.mode = "1";
        CardLove.Config.step = 3;
        CardLove.Game.showStatus({
            msg:"系统准备出牌，剩下",
            time:CardLove.Config.timer.showSysCardTimer - this._showSysCardTime,
            color:"#FFF"
        });

        //显示系统card牌前，不能选牌
        CardLove.Config.game.mode = "-1";

        this._showSysCardTime++;
        this._showSysCardFlag =  setTimeout("CardLove.Game.showSysCard()",1000);
    }else{
    	CardLove.Card.sysShowCard();
    	 this._showSysCardTime =0;
        clearTimeout(this._showSysCardFlag);

        CardLove.Config.game.mode = "-1";
		CardLove.Game.pickerCard();
    }
};

/**
 * 第5步：role选择card牌
 */
CardLove.Game.pickerCard = function(){
    if(this.debug) debug.info("role选择card牌，当前第" + this._pickerTime + "秒");

	CardLove.Config.game.mode = "1";
    //AI随机时间
	var aiPickerTime = CardLove.Config.timer.aiPickerTime;
	if(!aiPickerTime){
    	aiPickerTime = CardLove.Config.timer.aiPickerTime = CardLove.Config.timer.pickerCardTimer * Math.random();
	}
    if(this._pickerTime == 0 || this._pickerTime < aiPickerTime){

        //card牌逻辑入口
        //CardLove.Game.checkCard();
    	
       	this._pickerTime++;
        this._pickerCardFlag = setTimeout("CardLove.Game.pickerCard()",3000);
    	
    }else{
        //clearTimeout(this._pickerCardFlag);
    	var _cache = CardLove.Card._cache;
		var card = _cache.cards[_cache.sysCurrentShowCard];//获取当前的card对象
		var cardList =( card.type == 0 ? _cache.playContainers : _cache.sysContainers);
		
		CardLove.Game.selectCard(cardList[card.areaIndex-1],true,{card:card}); 
		 this._pickerTime = 0;
		 CardLove.Config.timer.aiPickerTime = '';
        //超时AI选择card牌
        CardLove.Game.aiPickerCard();
		
    }

};

/**
 * 判断用户选择card牌逻辑
 */
CardLove.Game.checkCard = function(){
	
	
    //下一轮轮开始
   // CardLove.Game.showSysCard();
};

/**
 * 超时AI随机选择一张牌
 */
CardLove.Game.aiPickerCard = function(){
	CardLove.Config.game.mode ='-1';
	var _cache = CardLove.Card._cache;
	var num = 0;
	var cardInfo = null;
	var cotainer =null;
	var randSelect = function(){
		var flag = true;
		while(flag){
			var num = Math.ceil(Math.random()*12+0);
			cotainer = num > 6 ? _cache.playContainers[num -6] : _cache.sysContainers[num];
			cardInfo = CardLove.Game._getCardInfo(cotainer); //节点容器信息
			cardInfo.hasCard && (flag = false);
		}
	}
	var nodeInfo = CardLove.Config.imgList.node[1];
	var card = _cache.cards[cardInfo.id];//获取当前的card对象
	CardLove.Game.selectCard(cotainer,false,{card : card})
};
/**
 * 从容器节点上得到卡片信息
 * @param {String} containerNode
 * @private 
 * @return {Object} 
 */
CardLove.Game._getCardInfo = function(containerNode){
	var info = containerNode.id.split('_');
	return {
		type : info[0] == 'player',
		id : info[2] || '',
		hasCard : jQuery(containerNode).find('img').length > 0
	};
}
/**
 * 得到卡牌容器的index
 * @param {Element} node
 * @return {Number} 索引 
 */
CardLove.Game._getIndex = function(node,isPlayer){
		var _cache=CardLove.Card._cache;
		return jQuery.inArray(node,isPlayer ? _cache.playContainers : _cache.sysContainers);
};
/**
 * 交换卡片
 * 需要两个选择的节点
 * 第一张和第二张不能是同一张卡片
 * CardLove.Config.game.mode = 0
 * @param {Element} node
 */
CardLove.Game.exchangeCard = function(node,isPlayer,opt){
	var _cache = opt._cache;
	var cardInfo = opt.cardInfo;
	var flag = opt.flag;
	var nodeInfo = opt.nodeInfo;
	if(!_cache.selectNode){
		if(!(cardInfo.type == isPlayer) || !cardInfo.hasCard){
			debug.info('必须选择己方的卡片');
			return 
		}
		_cache.selectNode = node;
		return false;
	}
	if(_cache.selectNode == node) return;
	var srcNode = _cache.selectNode.getElementsByTagName('img')[0];
	var targeNode = node.getElementsByTagName('img')[0];
	_cache.selectNode.appendChild(targeNode);
	node.appendChild(srcNode);
	_cache.selectNode = null;
	return ;
	
	CardLove.Card.exchange(CardLove.Game._getIndex(_cache.selectNode,isPlayer),CardLove.Game._getIndex(node,isPlayer),'exchagnge',isPlayer,function(){
			_cache.selectNode = null;
		});
};
/**
 * 拆牌
 * CardLove.Config.game.mode = 1
 * @param {Element} node 
 * @param {Boolean} isPlayer 是否是玩家进行操作
 */
CardLove.Game.selectCard = function(node,isPlayer,opt){
	var flag = isPlayer ? 0 : 1;
	var nodeInfo = CardLove.Config.imgList.node[flag];
	var card = opt.card;
	var result =  CardLove.Card.checkCard(card);
	var type = nodeInfo.tag == 'player' ? 0 : 1;
	if(result){
		if(card.type == type){//卡片放在玩家牌区
			//CardLove.Game.sendToScoring(node,true);
			CardLove.Config.game.mode = '-1';
			 
		}else{
			//CardLove.Game.sendToScoring(node,false);
			
			CardLove.Config.game.mode = '2';
		}
		CardLove.Game.showScoreCard(isPlayer);
		
		CardLove.Game.showSysCard();
	}else{
		if(card.type == nodeInfo.tag){
			CardLove.Config.game.mode = '2';
			ardLove.Game.showScoreCard(isPlayer);
			CardLove.Game.showSysCard();
		}
	}
	var role =isPlayer ?  CardLove.Game.player : CardLove.Game.system;
	role.score ++;
	var img = $(node).find('img').get(0);
	document.getElementById('scoring').appendChild(img);
};
/**
 * 送牌
 * 需要两个选择的节点,第一个是自己的卡片，另外一个是对方的卡牌空嘈
 * CardLove.Config.game.mode = 2
 * @param {Element} node 容器节点
 * @param {Boolean} isPlayer 是否是玩家进行操作
 */
CardLove.Game.sendCard = function(node,isPlayer,opt){
	var _cache = opt._cache;
	var cardInfo = opt._getCardInfo(node);
	var flag = opt.flag;
	var nodeInfo = opt.nodeInfo;
	if(!_cache.selectNode){
		if(!(cardInfo.type == nodeInfo.tag) || !cardInfo.hasCard){
			//TODO 提示信息 必须选择己方的卡片
			debug.info('必须选择己方的卡片');
			return 1;//选择自己的卡片
		}
		_cache.selectNode = node;
		//TODO 提示信息 请选择对方空的卡槽
		debug.info('等待第二个节点,请选择对方空的卡槽');
		return 0;//等待第二个节点
	}
	//第二个节点是个空卡槽
	if(!cardInfo.hasCard){//如果卡槽是空的则可以进行逻辑
		CardLove.Game.showScoreCard(isPlayer);
		var img = $(node).find('img').get(0);
		document.getElementById('scoring').appendChild(img);
		return ;
		CardLove.Card.exchange(CardLove.Game._getIndex(_cache.selectNode,isPlayer),CardLove.Game._getIndex(node,isPlayer),'send',isPlayer,function(){
			_cache.selectNode = null;
			CardLove.Game.showSysCard();
		});
		return 10;//成功发送图片
	}else{
		//TODO 提示信息 请选择空敌方空的卡槽
		debug.info('请选择空敌方空的卡槽');
		return -3;
	}
};
	
/**
 * 卡片送到得分区
 * @param {Element} node 需要送去得分区的容器节点
 * @param {Boolean} isPlayer 是否去玩家得分区
 */
CardLove.Game.sendToScoring = function(node,isPlayer){
	var index = CardLove.Game._getIndex(node,isPlayer);
	CardLove.Card.exchange(index,'scoring','send',isPlayer,function(){
		CardLove.Card._cache.selectNode = null;
		CardLove.Card._cache.cards[index].isInScoring = true;
		CardLove.Game.showSysCard();
	});
	return true;
};

CardLove.Game.initCanvas = function(){
	CardLove.Game.loadImg(CardLove.Config.canvasImg.src,function(images){
		CardLove.DrawImages(images[0].src, 0, 0, true);
		CardLove.Game.showScoreArea();
	});
}

CardLove.Game.loadImg = function(sources, callback){
	var images = {};
	var loadedImages = 0;
    var numImages = 0;

    for (var src in sources) {
        numImages++;
    }
    for (var src in sources) {

        images[src] = new Image();
        images[src].onload = function(){
			if (++loadedImages >= numImages) {
				callback(images);
			}
        };
        images[src].src = sources[src];
    }
}

CardLove.Game.showScoreArea = function(){
	var canvas = CardLove.Canvas();
	var cwidth = canvas.width();
	var cheight = canvas.height()
	var c = CardLove.Context();

	CardLove.DrawText("#fff", "对方得分牌存放区域", cwidth/2, 50);
	CardLove.DrawText("#fff", "我方得分牌存放区域", cwidth/2, 730);
}

CardLove.Game.showStatus = function(json){
	var m = json.msg + "：" + json.time + "秒";

	$("#msg").html(m);
}

CardLove.Game.showScoreCard = function(type){
	var canvas = CardLove.Canvas();
	var cwidth = canvas.width();
	var cheight = canvas.height()
	var c = CardLove.Context();

	//type：true为我方得分
	var x = 40;

	var cx = 0;
	var cy = 0;
	if(type){
		CardLove.Config.scoreCardLoc.x1 += x;
		cx =  CardLove.Config.scoreCardLoc.x1;
		cy = cheight-100;
	}else{
		CardLove.Config.scoreCardLoc.x2 -= x
		cx =  CardLove.Config.scoreCardLoc.x2;
		cy = 20;
	}	
	CardLove.DrawImages("img/cards/back.jpg", cx, cy, false);
};

/**
 * 判断是否有card牌
 * @param id
 */
CardLove.Game.hasCard = function(id){
    if($(id+" div img").length==0){
        return true;
    }else{
        return false;
    }
};

/**
 * 判断自己输赢
 */
CardLove.Game.isWin = function(){
	var player = CardLove.Game.player;
	if(player.score>=6){
		return true;
	}
};

CardLove.Game.isLose = function(){
	var sys =	CardLove.Game.system;
	if(sys.score>=6){
		return false;
	}
}